package com.yunchao.app

import com.yunchao.library.http.ApiResultAdapterFactory
import me.jessyan.retrofiturlmanager.RetrofitUrlManager
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.module
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit

private const val TIME_OUT = 60L


internal val appModule = module {

    single {
        HttpLoggingInterceptor { message ->
            Timber.d("Http: $message")
        }.apply {
            level = HttpLoggingInterceptor.Level.BODY
        }
    }

    single {
        RetrofitUrlManager.getInstance().with(
            OkHttpClient().newBuilder().apply {
                callTimeout(TIME_OUT, TimeUnit.SECONDS)
                connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                readTimeout(TIME_OUT, TimeUnit.SECONDS)
                writeTimeout(TIME_OUT, TimeUnit.SECONDS)
                retryOnConnectionFailure(true)
                followRedirects(false)
                addInterceptor(get<HttpLoggingInterceptor>())
            }
        ).build()
    }


    single {
        Retrofit.Builder()
            .baseUrl(BuildConfig.GRADLE_API_BASE_URL)
            .client(get())
            .addConverterFactory(GsonConverterFactory.create(get()))
            .addCallAdapterFactory(ApiResultAdapterFactory())
            .build()
    }
}